//
//  XGSettingTableViewCell.m
//  Lottery
//
//  Created by monkey on 2018/10/4.
//  Copyright © 2018 itcast. All rights reserved.
//

#import "XGSettingTableViewCell.h"

#import "XGSettingItemModel.h"

@interface XGSettingTableViewCell ()

/** 数据模型 */
@property (nonatomic,strong) XGSettingItemModel *itemModel;

/** 开关 */
@property (nonatomic,strong) UISwitch *switchView;

@end

@implementation XGSettingTableViewCell

#pragma mark - 解析模型

- (void)setItemModel:(XGSettingItemModel *)itemModel
{
    _itemModel = itemModel;
    
    // 设置图片
    if (itemModel.icon != nil) {
        self.imageView.image = [UIImage imageNamed:itemModel.icon];
    }
    
    // 设置标题
    self.textLabel.text = itemModel.title;
    
    // 设置子标题
    if (itemModel.subTitle != nil) {
        self.detailTextLabel.text = itemModel.subTitle;
    } else {
        self.detailTextLabel.text = nil;
    }
    
    // 设置辅助视图
    if ([itemModel.accessoryType isEqualToString:@"UISwitch"]) {
        self.accessoryType = UITableViewCellAccessoryNone;
        self.accessoryView = self.switchView;
        self.switchView.on = itemModel.switchState;
    } else {
        self.accessoryType = UITableViewCellAccessoryNone;
        self.accessoryView = nil;
    }
}

#pragma mark - 监听方法

- (void)switchValueChanged:(UISwitch *)switchView
{
    // 保存按钮的状态
    self.itemModel.switchState = switchView.isOn;
}

#pragma mark - 构造方法

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.textLabel.font = [UIFont systemFontOfSize:20];
        self.detailTextLabel.textColor = [UIColor lightGrayColor];
    }
    
    return self;
}

+ (instancetype)cellForTableView:(UITableView *)tableView itemModel:(XGSettingItemModel *)itemModel
{
    // 获取cell类型
    NSString *reuseIdentifier = itemModel.tableViewCellStyle;
    UITableViewCellStyle cellStyle = [self tableViewCellStyleWithStyle:itemModel.tableViewCellStyle];
    
    // 创建cell
    XGSettingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (cell == nil) {
        cell = [[self alloc] initWithStyle:cellStyle reuseIdentifier:reuseIdentifier];
    }
    
    // 设置模型
    cell.itemModel = itemModel;
    return cell;
}

+ (UITableViewCellStyle)tableViewCellStyleWithStyle:(NSString *)style
{
    if ([style isEqualToString:@"UITableViewCellStyleSubtitle"]) {
        return UITableViewCellStyleSubtitle;
    } else if ([style isEqualToString:@"UITableViewCellStyleValue1"]) {
        return UITableViewCellStyleValue1;
    } else {
        return UITableViewCellStyleDefault;
    }
}

#pragma mark - 懒加载

- (UISwitch *)switchView
{
    if (!_switchView) {
        _switchView = [[UISwitch alloc] init];
        [_switchView addTarget:self action:@selector(switchValueChanged:) forControlEvents:UIControlEventValueChanged];
    }
    
    return _switchView;
}

@end
